﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Hangout.Web.Core.Tokens
{
    public class Tokens
    {
        public static Model.Token InsertTokenIfNotExists(string tokenname,ref Model.HangoutDBEntities context)
        {
            Model.Token token = context.Tokens.Where(o => o.TokenName == tokenname.ToLower()).FirstOrDefault();

            if (token == null)
            {
                token = new Model.Token();
                token.TokenName = tokenname.ToLower();
                token.TokenDescription = "";

                context.AddToTokens(token);

                context.SaveChanges();
            }

            return token;
        }

        public static void AddUserToken(int userid,int tokenId,ref Model.HangoutDBEntities context)
        {
           if(!UserTokenExists(userid,tokenId,context))
           {
               Model.UserToken t=new Model.UserToken();
               t.TokenId=tokenId;
               t.UserId=userid;
               t.Score=1;

               context.AddToUserTokens(t);

               context.SaveChanges();
              
           }
        }

        public static void AddUserToken(int userid, int tokenId,int incScore, ref Model.HangoutDBEntities context)
        {

                Model.UserToken t = context.UserTokens.Where(o => o.UserId == userid && o.TokenId == tokenId).FirstOrDefault();
                if (t != null)
                {
                    t.Score += incScore;
                    context.SaveChanges();
                }

            
        }

        

        public static bool UserTokenExists(int userId, int tokenId, Model.HangoutDBEntities context)
        {
            if (context.UserTokens.Where(o => o.UserId==userId && o.TokenId==tokenId).Count() > 0)
            {
                return true;
            }
            return false;
        }

        public static void IncreaseTokenScore(List<string> tokens, int score, int userId, ref Model.HangoutDBEntities context)
        {
            foreach (string s in tokens)
            {
                Model.Token token = InsertTokenIfNotExists(s, ref context);
                AddUserToken(userId, token.TokenId, score, ref context);
            }
        }
    }
}